/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;

/**
 * 
 * @author Yang Wang <yang@digitalmenubox.com>
 */
public class ImagePreloader extends SwingWorker<Void, BufferedImage> {

	List<BufferedImage> images = new ArrayList<BufferedImage>();
	JFrame f;

	public ImagePreloader(JFrame f) {
		this.f = f;
	}

	public static void main(String[] args) throws Exception {
		final JFrame frame = new JFrame("test");
		frame.setBounds(100, 100, 300, 300);
		frame.add(new JLabel("asdf"));
		frame.setVisible(true);

		ImagePreloader iLoader = new ImagePreloader(frame);
		System.out.println(new Date().getTime() + " start");
		iLoader.execute();
	}

	@Override
	protected Void doInBackground() {
		File dir = new File("resources/images/");
		File[] files = dir.listFiles();
		System.out.println(Arrays.toString(dir.list()));
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			System.out.println(new Date().getTime() + " reading file " + file);
			BufferedImage bi = null;
			try {
				bi = ImageIO.read(file);
			} catch (IOException ex) {
				Logger.getLogger(ImagePreloader.class.getName()).log(Level.SEVERE, null, ex);
			}
			this.publish(bi);
			this.images.add(bi);
		}
		return null;
	}

	@Override
	protected void done() {
		JLabel l = new JLabel(new ImageIcon(this.images.get(this.images.size() - 1)));
		// l = new JLabel("asdfaaaaaaaaaa");
		JPanel jp = new JPanel();
		jp.add(l);
		this.f.setContentPane(jp);
		this.f.validate();
		System.out.println(new Date().getTime() + " done");
	}

	@Override
	protected void process(List<BufferedImage> chunks) {
		super.process(chunks);
	}

}
